import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_login.dart';
import 'package:gold/http/http.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';

/// @description:
/// @author tangzhentao
/// @created at 10:38 2024/12/15


class WithdrawalViewmodel extends Viewmodel {
  /// 提现金额
  final TextEditingController moneyController = TextEditingController();
  final FocusNode moneyNode = FocusNode();

  double _balance = 0;
  /// 余额
  double get balance => _balance;

  String? _wechat;
  /// 微信名称
  String? get wechat => _wechat;
  set wechat(String? value) {
    if (_wechat != value) {
      _wechat = value;
      onChanged(moneyController.text, notify: false);
      notifyListeners();
    }
  }

  bool _canClick = false;
  /// 是否可点击
  bool get canClick => _canClick;

  WithdrawalViewmodel() {
    _balance = XfgNav.read<UserProvider>().user.amount?? 0.00;
  }

  /// 绑定微信账号
  Future bindWechat() async {
    final random = Random().nextInt(1000000);
    wechat = random.toString();
  }

  /// 提现金额变化
  void onChanged(String value, {bool notify = true}) {
    final money = double.tryParse(value) ?? 0;
    final click = money >= 1 && money < _balance && _wechat?.isNotEmpty == true;
    bool changed = false;
    if (_canClick != click) {
      _canClick = click;
      changed = true;
    }
    if (changed && notify) notifyListeners();
  }

  /// 提现记录
  void withdrawalDetails() {
    XfgNav.pushNamed(Routes.myWithdrawalDetails);
  }

  /// 提现到微信余额
  Future withdrawalWechat() async {
    hideKeyboard();
    final result = await Http().request<dynamic>(ApiLogin.withdrawalCreate, loadingText: '提现中...', data: {'amount': moneyController.text});
    if (result.success) {
      _canClick = false;
      _balance = _balance - (double.tryParse(moneyController.text) ?? 0);
      notifyListeners();
      moneyController.text = '';
      XfgNav.read<UserProvider>().updateProfile();
      XfgNav.pushNamed(Routes.myWithdrawalSuccess);
    }
  }
}